<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.keyword" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getPets">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="offsale">下架</el-button>
        </el-form-item>

      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="pets" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="宠物名字" width="120" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="成本价" width="100"  sortable>
      </el-table-column>
      <el-table-column prop="saleprice" label="售卖价" width="100"  sortable>
      </el-table-column>
      <el-table-column prop="resourcess" label="资源" width="100"  sortable>
      </el-table-column>
      <el-table-column prop="typeName" label="宠物类型" width="100"  sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <span v-if="scope.row.state==0" style="color: red">下架</span>
          <span v-else-if="scope.row.state==1" style="color: green">上架</span>
          <span v-else style="color: red">未知</span>
        </template>
      </el-table-column>
      <el-table-column prop="shopName" label="所属店铺" width="100" sortable>
      </el-table-column>
      <el-table-column prop="adoptName" label="领养人" width="120" sortable>
      </el-table-column>
      <el-table-column prop="offsaletime" label="上架时间" width="120" sortable>
      </el-table-column>
      <el-table-column prop="onsaletime" label="下架时间" width="120" sortable>
      </el-table-column>
      <el-table-column prop="searchMasterMsgId" label="宠物来源" width="100" sortable>
        <template scope="scope">
          <span v-if="scope.row.searchMasterMsgId==null" style="color: green">店铺饲养</span>
          <span v-else-if="scope.row.searchMasterMsgId==1" style="color: red">寻主消息</span>
          <span v-else style="color: red">未知</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :current-page="currentPage"
                     :page-size="pageSize"
                     :total="total"
                     style="float:right;">
      </el-pagination>
    </el-col>


    <!--新增界面-->
    <el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="saleprice">
          <el-input v-model="addForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售卖价" prop="costprice">
          <el-input v-model="addForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="上架时间">
          <el-date-picker type="date" placeholder="选择日期" v-model="addForm.offsaletime"></el-date-picker>
        </el-form-item>
        <el-form-item label="下架时间">
          <el-date-picker type="date" placeholder="选择日期" v-model="addForm.onsaletime"></el-date-picker>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="addForm.state">
            <el-radio class="radio" :label="1">上架</el-radio>
            <el-radio class="radio" :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="宠物类型">
          <!--<el-input auto-complete="off" v-model="editForm.parent"></el-input>-->
          <el-cascader v-model="addForm.typeId"
                       :options="petTypeTree"
                       :props="{
								checkStrictly: true,
								value:'id',
								label:'name'
							 }"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="资源" prop="resources">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastDfs"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.petDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor  v-model="addForm.petDetail.intro" v-if="addForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor  v-model="addForm.petDetail.adoptNotice" v-if="addForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import { getPetListPage, removePet, batchRemovePet, editPet, addPet } from '../../api/api';
//引入Vue的ueditor的资源
import { quillEditor } from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';

export default {
  components: {
    quillEditor
  },
  data() {
    return {
      //文件上传列表 - 资源resources
      fileList:[],
      quillOption: quillConfig,
      filters: {
        keyword: ''
      },
      pets: [],
      page: 1,
      listLoading: false,
      sels: [],//列表选中列
      currentPage:1,
      pageSize:5,
      total: 0,
      petTypeTree:[],
      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      //编辑界面数据
      editForm: {
        id: 0,
        name: '',
        sex: -1,
        age: 0,
        birth: '',
        addr: '',

      },

      addFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ]
      },
      //新增界面数据
      addForm: {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        typeId: null,
        resources: '',
        state: 0, //默认下架 - 前台看不见这个宠物 - 审核之后才能上架
        shopId: null,
        petDetail:{  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        },
        onsaletime:'',
        offsaletime:'',
      }
    }
  },
  methods: {
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPets();
    },
    //获取宠物列表
    getPets() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.filters.keyword
      };
      this.listLoading = true;
      //NProgress.start();
      this.$http.post("/pet",para)
          .then(result=>{
            this.total = result.data.totals;
            this.pets = result.data.rows;
            console.log(result)
            this.listLoading = false;

          })
          .catch(result=>{

          })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        let para = { id: row.id };
        this.$http.delete("/pet/"+row.id)
            .then(result=>{
              this.listLoading = false;
              result = result.data;
              if(result.success){
                this.$message({
                  message: result.message,
                  type: 'success'
                });
                this.currentPage = 1;
                this.getPets();
              }else{
                this.$message({
                  message: result.message,
                  type: 'err'
                });
                this.listLoading = false;
                this.getPets();
              }
            })
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {

      //alert(row.roleId);
      this.getPets();
      this.addFormVisible = true;
      //回显数据：避免以前的数据发生改变
      this.addForm = Object.assign({}, row);
      this.title = "修改";
      //加载所有店铺 - 方便选择宠物的所属店铺
      this.getShops();
      this.getPetTypeTree();

      //处理fileList - 点击修改能够回显图片
      this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
      if(this.addForm.resources){
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
        var arr = this.addForm.resources.split(",");
        for(var i = 0;i<arr.length;i++){
          var item = arr[i]; ///group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }
      //显示详情：两种方案：1.直接在分页查询时就把详情一并查询出来  2.点击编辑按钮弹出模态框的时候单独查询

      //显示对话框
      this.addFormVisible = true;
    },
    //显示新增界面
    handleAdd: function () {
      this.title = "添加";
      //重置表单
      this.addForm = {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        typeId: null,
        resources: '',
        state: 0, //默认下架 - 前台看不见这个宠物 - 审核之后才能上架
        shopId: null,
        petDetail:{
          intro: '',
          adoptNotice: ''
        }
      };
      //加载所有店铺 - 方便选择宠物的所属店铺
      this.getShops();
      this.getPetTypeTree();

      //清空fileList的数据
      this.fileList = [];
      //显示对话框
      this.addFormVisible = true;
    },
    //图片上传成功之后的回调
    handleSuccess(response, file, fileList){
      //Object { success: true, msg: "操作成功", resultObj: "/group1/M00/00/E4/CgAIC2Lc91yAK-XNAAVL-CQTDAM697.jpg" }
      //1.对resources的处理 - 添加到数据库
      if(this.addForm.resources){//有值返回true
        this.addForm.resources = this.addForm.resources + "," + response.resultObj;
      }else{
        this.addForm.resources = response.resultObj;
      }

      //2.对fileList的处理 - 前端显示图片的
      this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
      if(this.addForm.resources){
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
        var arr = this.addForm.resources.split(",");
        for(var i = 0;i<arr.length;i++){
          var item = arr[i]; ///group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }
    },
    handleRemove(file, fileList){
      //1.调用删除接口删除图片
      //Object { url:"http://123.207.27.208/group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg"}
      //console.log(file);
      //http://localhost:8080/fastDfs?path=/group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
      var path = file.url.substring(file.url.indexOf("/group")); //  /group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg
      this.$http.delete("/fastDfs?path="+path).then(res=>{
        if(res.data.success){
          this.$message.success("删除成功")
        }else{
          this.$message.error("删除失败")
        }
      })

      //2.对resource做处理
      // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/E5/CgAIC2Lc_7qAPinhAAEau2OL7dM844.jpg,/group1/M00/00/09/rBEACmKXF8-AUc6KAANsldwx3H4713.jpg
      if(this.addForm.resources){
        var arr = this.addForm.resources.split(",");
        for(var i = 0;i<arr.length;i++){
          var item = arr[i];
          if(path==item){//找到了删除的图片
            arr.splice(i,1);//删除指定的图片
          }
        }
        this.addForm.resources = arr.join(",")
      }


      //3.对fileList的处理 - 前端显示图片的
      this.fileList = []; //先清空 - 这个fileList做了绑定，以前是有值【先清空，再添加最新的数据】
      if(this.addForm.resources){
        // /group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg,/group1/M00/00/0C/CgAIC2KrUYaAaR-6AADnxcxs4eA746.jpg
        var arr = this.addForm.resources.split(",");
        for(var i = 0;i<arr.length;i++){
          var item = arr[i]; ///group1/M00/00/0C/CgAIC2KrUU-ARA8EAAH2I5Y672k716.jpg
          this.fileList.push({"url":"http://123.207.27.208" + item});
        }
      }
    },
    getShops(){
      let paras = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true;
      this.$http.post("/shop",paras).then(res=>{
        this.totals = res.data.totals;
        this.shops = res.data.rows;
        this.listLoading = false;
      }).catch(res => {
        this.$message.error("获取分页数据失败!!!");
      })
    },
    //新增或修改
    addSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.addForm);
            if(para.typeId){
              para.typeId =para.typeId[para.typeId.length-1];
            }
            this.$http.put("/pet",para)
                .then(result=>{
                  this.addLoading = false;
                  result = result.data;
                  if(result.success){
                    this.$message({
                      message: result.message,
                      type: 'success'
                    });
                    this.currentPage = 1;
                    this.getPets();
                    this.addFormVisible = false;
                  }else{
                    this.$message({
                      message: result.message,
                      type: 'error'
                    });
                  }
                })
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //NProgress.start();
        //let para = { ids: ids };
        this.$http.patch("/pet",ids)
            .then(result=>{
              this.listLoading = false;
              result = result.data;
              if(result.success){
                this.$message({
                  message: result.message,
                  type: 'success'
                });
                this.currentPage = 1;
                this.getPets();
              }else{
                this.$message({
                  message: result.message,
                  type: 'err'
                });
                this.getPets();
              }
            })
            .catch(result=>{
              this.$message({
                message: '系统繁忙，稍后重试',
                type: 'err'
              });
            })
      }).catch(() => {

      });
    },
    getPetTypeTree(){
      this.$http.get("/petType/petTypetree")
          .then(result=>{
            this.petTypeTree = result.data;
          })
    },
    //上架
    onsale(){
      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾上架不了啊....',type: 'error'});
        return;
      }
      this.$confirm('确认上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/pet/onsale',ids).then((res) => {
          this.listLoading = false;
          if(res.data.success){
            this.$message({
              message: '上架成功',
              type: 'success'
            });
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getPets();
        }).catch(res => {
          this.$message({
            message: "系统错误，请稍后重试!!!",
            type: 'error'
          });
        })
      }).catch(() => {
      });
    },

//下架
    offsale(){
      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾下架不了啊....',type: 'error'});
        return;
      }
      this.$confirm('确认下架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post('/pet/offsale',ids).then((res) => {
          this.listLoading = false;

          if(res.data.success){
            this.$message({
              message: '下架成功',
              type: 'success'
            });
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getPets();
        }).catch(res => {
          this.$message({
            message: "系统错误，请稍后重试!!!",
            type: 'error'
          });
        })
      }).catch(() => {
      });
    },
  },
  mounted() {
    this.getPets();
    this.getPetTypeTree();
  }
}

</script>

<style scoped>

</style>